package org.kolonitsky.css.runner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.jetbrains.annotations.Nullable;
import org.kolonitsky.css.CssToXml;
import org.kolonitsky.css.cssdoc.XmlToCssDoc;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;

import static org.apache.commons.io.FileUtils.getFile;
import static org.apache.commons.io.FileUtils.openOutputStream;

/**
 * @author Alex.Kolonitsky
 */
public class Runner {

    private final Settings settings;

    public Runner(Settings settings) {
        this.settings = settings;
    }

    public void run() {
        copyTemplateToOutputFolder();

        xmlToHtml(cssToXml(getCssFiles()));
    }

    private void xmlToHtml(Collection<File> xmlFiles) {
        XmlToCssDoc toCssDoc = new XmlToCssDoc(settings.xslt(), settings.htmlOutputFolder());
        toCssDoc.generateReports(xmlFiles);
    }

    private void copyTemplateToOutputFolder() {
        try {
            FileUtils.copyDirectory(settings.htmlTemplateFolder(), settings.htmlOutputFolder());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected Collection<File> cssToXml(Collection<File> cssFiles) {
        Collection<File> files = new ArrayList<File>(cssFiles.size());
        for (File cssFile : cssFiles) {
            File file = cssToXml(cssFile);
            if (file != null) {
                files.add(file);
            }
        }
        return files;
    }

    @Nullable
    private File cssToXml(File cssFiles) {
        try {
            if (!settings.xmlOutputFolder().exists()) {
                FileUtils.forceMkdir(settings.xmlOutputFolder());
            }

            File xmlFile = FileUtils.getFile(settings.xmlOutputFolder(), FilenameUtils.getBaseName(cssFiles.getName()) + ".xml");
            CssToXml.generateXml(new FileReader(cssFiles), new FileWriter(xmlFile));

            return xmlFile;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Collection<File> getCssFiles() {
        return FileUtils.listFiles(settings.cssInputFolder(), new String[]{"css"}, true);
    }

    public Settings getSettings() {
        return settings;
    }
}
